/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fuzzy.actions;

import fuzzy.hibernate.HibernateUtil;
import fuzzy.hibernate.Uzytkownicy;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionRedirect;
import org.hibernate.Query;
import org.hibernate.Session;

/**
 *
 * @author kaqu
 */
public class LoginAction extends org.apache.struts.action.Action {

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";
    private static final String FAILURE = "failure";

    /**
     * This is the action called from the Struts framework.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        Session currentSession = HibernateUtil.getSession();
        currentSession.beginTransaction();
        LoginFormBean loginBean = (LoginFormBean)form;
        Query q = currentSession.createQuery("FROM Uzytkownicy WHERE login = :username AND haslo = :password");
        q.setParameter("username", loginBean.getName());
        q.setParameter("password", loginBean.getPass());
        
        List<Uzytkownicy> lista =  q.list();
        
        // Sprawdzamy, czy hibernate znalazł użytkownika.
        if (!lista.isEmpty()) {
            Uzytkownicy user = lista.get(0);
            HttpSession session = request.getSession();
            // Zapisujemy użytkownika w sesji.
            session.setAttribute("user", user);
            
            ActionRedirect redirect = new ActionRedirect(mapping.findForward(SUCCESS));
            return redirect;
        }
        
        ActionErrors errors = new ActionErrors();
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("login.badcredentials"));
        saveErrors(request, errors);
        return mapping.findForward(FAILURE);
    }
}
